package com.cml.rpc.server;


import com.cml.rpc.publicpojo.RpcRequest;
import com.cml.rpc.publicpojo.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

/**
 * 处理请求的线程
 * @author cml
 * @create 2021/7/21 9:37
 */
public class WorkThread implements Runnable {
    private Socket socket;
    private Map<String, Object> serviceProvide;

    public WorkThread(Socket socket, Map<String, Object> serviceProvide) {
        this.socket = socket;
        this.serviceProvide = serviceProvide;
    }

    @Override
    public void run() {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
            // 接收客户端请求
            RpcRequest rpcRequest = (RpcRequest)ois.readObject();
            // 处理请求
            RpcResponse rpcResponse = handlerRequest(rpcRequest);
            System.out.println("响应数据rpcResponse = " + rpcResponse);
            // 将处理结果响应客户端
            oos.writeObject(rpcResponse);
            oos.flush();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("从IO中读取数据出错");
        }

    }

    /**
     * 处理请求
     * @param rpcRequest
     * @return
     */
    private RpcResponse handlerRequest(RpcRequest rpcRequest) {
        // 从请求中得到相应数据
        String interfaceName = rpcRequest.getInterfaceName();
        String methodName = rpcRequest.getMethodName();
        Object[] params = rpcRequest.getParams();
        Class<?>[] paramTypes = rpcRequest.getParamTypes();
        // 得到对应服务实现类
        Object server = serviceProvide.get(interfaceName);
        Method method = null;
        try {
            // 反射执行对应方法
            method = server.getClass().getMethod(methodName, paramTypes);
            Object result = method.invoke(server, params);
            return RpcResponse.success(result);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            System.out.println("方法执行错误");
            return RpcResponse.fail();
        }
    }
}
